<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../js/vue.js"></script>
</head>

<body>
  <div id="app">
    <div v-if="books.length">
      <table>
        <thead>
          <tr>
            <th></th>
            <th>名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in books">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.price | showPrice}}</td>
            <td><button @click="jian(index)" :disabled="item.count <= 1">-</button>{{item.count}}<button @click="jia(index)">+</button></td>
            <td><button @click="remove(index)">移除</button></td>
          </tr>
        </tbody>
      </table>
      <div>总价格:{{totalPrice | showPrice}}</div>
    </div>
    <h2 v-else>购物车空</h2>
  </div>
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        books: [{
          id: 1,
          name: '小林',
          price: 10,
          count: 1,
        }, {
          id: 2,
          name: '小书本',
          price: 3.23,
          count: 1,
        }, {
          id: 3,
          name: '三国',
          price: 10.11,
          count: 1,
        }],
      },
      methods: {
        jian(index) {
          this.books[index].count--
        },
        jia(index) {
          this.books[index].count++
        },
        remove(index) {
          this.books.splice(index, 1)
        }
      },
      //计算属性
      computed: {
        totalPrice() {
          let totalPrice = 0
          const books = this.books
            // 1
            // for (let i = 0; i < books.length; i++) {
            //     totalPrice += books[i].price * books[i].count
            // }
            // 2
            // for (let i in books) {
            //     console.log(i)
            //     totalPrice += books[i].price * books[i].count
            // }
          for (let item of books) {
            // console.log(item)
            totalPrice += item.price * item.count
          }

          // filter/map/reduce
          return totalPrice
        }
      },
      // 过滤属性
      filters: {
        showPrice(price) {
          return '￥' + price.toFixed(2)
        }
      }
    })
  </script>
</body>

</html>